/* ==============================================================================
*
*   Copyright (c) 2010, Pierre Favier
*   All rights reserved.
*
*   NTasking is free software: you can redistribute it and/or modify it
*   under the terms of the GNU General Public License as published by the
*   Free Software Foundation.
*
*   Redistribution and use in source and binary forms, with or without
*   modification, are permitted provided that the following conditions
*   are met:
*
*   -   Redistributions of source code must retain the above copyright notice,
*       this list of conditions and the following disclaimer.
*
*   -   Redistributions in binary form must reproduce the above
*       copyright notice, this list of conditions and the following
*       disclaimer in the documentation and/or other materials
*       provided with the distribution.
*
*   THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
*   WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
*   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
*   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
*   BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
*   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
*   TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
*   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
*   ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
*   TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
*   THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
*   SUCH DAMAGE.
*
* ============================================================================== */

using System;
using System.Threading;
using NTasking.ValidationTests.ACATS_3_0.Support;
using NUnit.Framework;
using Rhino.Mocks;

namespace NTasking.ValidationTests.ACATS_3_0.C9
{

    [TestFixture(Description = "")]
    public class C9740002 : ValidationTest
    {

        private static bool AbortablePartExecuted;
        private static bool TriggeringAlternativeExecuted;


        private static bool Equal(int left, int right)
        {
            return left == right;
        }


        private static void QuickCalculation()
        {
            if (Equal(1, 1))
            {
                AbortablePartExecuted = true; // allow other task 
            }
        }


        internal class TimedCalculation : ValidationTestTask
        {

            [Entry]
            internal Action<DateTime> Calculation { get; private set; }


            internal TimedCalculation(IValidationTestResult result)
                : base(result)
            {
                Name = "TimedCalculation";
            }


            protected override void Body()
            {
                while (true)
                {

                    Select(s => s.
                        Accept(Calculation, (timeOut) =>
                        {

                            // Asynchronous select is tested here

                            Ada.Select(s2 => s2.
                                // Triggering statement.
                                Delay(timeOut).
                                // Triggering alternative
                                Then(() =>
                                {
                                    TriggeringAlternativeExecuted = true;
                                    TriggeringAlternativeExecuted = true;
                                }).
                            ThenAbort(() =>
                            {
                                // Abortable part
                                QuickCalculation();
                            }));
                        }).
                    Or.
                        Terminate
                    );

                }
            }
            protected override void Exception(Exception ex)
            {
                // Unexpected exception in Timed_Calculation task
                Result.TestFailed();
            }

        }


        [Test(Description =
            "Check that the abortable part of an asynchronous select statementt" +
            "is aborted if it does not complete before the triggering statementt" +
            "completes, where the triggering statement is a delay_relativet" +
            "statement and check that the sequence of statements of the triggering t" +
            "alternative is executed after the abortable part is left.")]
        public void Test()
        {
            IValidationTestResult result = Mocks.DynamicMock<IValidationTestResult>();

            TimedCalculation timed = null;

            // Setup test expectations

            Expect.Call(result.TestFailed).Repeat.Never();

            Mocks.ReplayAll();

            Ada.Declare(() =>
            {
                AbortablePartExecuted         = false;
                TriggeringAlternativeExecuted = false;

                timed = new TimedCalculation(result);
            },
            Begin: () =>
            {
                DateTime expiry = new DateTime(1901, 01, 01);

                // Start test execution
                timed.Calculation(expiry);

                if (AbortablePartExecuted)
                    result.TestFailed();

                if (!TriggeringAlternativeExecuted)
                    result.TestFailed();
            });

            Ada.Declare(() =>
            {
                AbortablePartExecuted = false;
                TriggeringAlternativeExecuted = false;

                timed = new TimedCalculation(result);
            },
            Begin: () =>
            {
                const int Minute = 60;
                DateTime expiry = DateTime.Now.AddSeconds(Minute);

                // Start test execution
                timed.Calculation(expiry);

                if (!AbortablePartExecuted)
                    result.TestFailed();

                if (TriggeringAlternativeExecuted)
                    result.TestFailed();
            });

        }

    }

}
